/**
 * Created by huotaol on 2017/9/30.
 */
import {Button, DatePicker, Form, Input, Modal, Select, Table} from "antd";
import React from "react";
import {connect} from "react-redux";
import {fetchData, receiveData} from "@/action";
import {get} from "@/axios/tools";
import moment from "moment";
import {bindActionCreators} from "redux";
import PayBill from "@/components/form/PayBill";

const {MonthPicker, RangePicker} = DatePicker;
const FormItem = Form.Item;
const Option = Select.Option;
const DEFAULT_PAGE_SIZE = 15;
const FORMAT_DATE = 'YYYY-MM-DD HH:mm';

class OrderList extends React.Component {
    // 构造
    constructor(props) {
        super(props);
        // 初始状态
        this.state = {
            data: [],
            currentPage: 1,
            total: 0,
            payBillShow: false,
        };
        this.searchData = {pageSize: DEFAULT_PAGE_SIZE};
        this.page = 1;
        this.payBillData = {};
    }

    componentDidMount() {
        // To disabled submit button at the beginning.
        this.submit();
    }

    handleSubmit = (e) => {
        e.preventDefault();
        this.submit();
    };

    submit() {
        this.props.form.validateFields((err, values) => {
            if (!err) {
                console.log('Received values of form: ', values);
                let {time, ...data} = values;
                if (time && time.length) {
                    data = {
                        ...data,
                        createTime: time[0].format(FORMAT_DATE),
                        endTime: time[1].format(FORMAT_DATE),
                    }
                }
                this.searchData = {...this.searchData, ...data};
                this._requestData(1);
            }
        });
    }

    _requestData = (page) => {
        const {auth: auth = {data: {}}} = this.props;
        if (auth.data.restaurant) {
            get('/order/listItem', {...this.searchData, restaurantID: auth.data.restaurant, page: page}).then(data => {
                console.log(' _requestData', data);
                const dataSource = data.data.map(item => {
                    return {...item, key: item.id};
                });
                this.setState({data: dataSource, total: data.total});
            });
        }
    };


    render() {
        const {getFieldDecorator, getFieldsError, getFieldError, isFieldTouched} = this.props.form;
        const columns = [{
            title: 'ID',
            dataIndex: 'id',
            key: 'id'
        }, {
            title: '买单',
            key: 'payBill',
            render: (text, data) => {
                return <Button
                    disabled={data.status === 'DONE'}
                    onClick={e => {
                        this.payBillData = data;
                        console.log('OrderList data    ', data);
                        this.setState({payBillShow: true});
                    }
                    }>买单</Button>
            }
        }, {
            title: '总价（¥）',
            dataIndex: 'cost',
            key: 'cost'
        }, {
            title: '收入（¥）',
            dataIndex: 'income',
            key: 'income'
        }, {
            title: '找零（¥）',
            dataIndex: 'change',
            key: 'change'
        }, {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            render: text => {
                if (text === 'CANCEL') {
                    return '取消';
                } else if (text === 'DOING') {
                    return '正在执行';
                } else if (text === 'DONE') {
                    return '完成';
                }
                return '';
            }
        }, {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
            render: (text) => {
                return moment(text).format(FORMAT_DATE);
            }
        }, {
            title: '餐桌或包房编号',
            dataIndex: 'tableOrRoom',
        }, {
            title: '结算员',
            dataIndex: 'userName',
            key: 'userName',
        }];
        const foodColumns = [{
            title: '菜品名',
            dataIndex: 'foodName'
        }, {
            title: '数量',
            dataIndex: 'num'
        }, {
            title: '状态',
            dataIndex: 'status'
        }];
        return (
            <div className="content-container">
                <Form layout="inline" onSubmit={this.handleSubmit}>
                    <FormItem
                        label={'订单状态'}
                    >
                        {getFieldDecorator('status', {
                            rules: [{required: false, message: '选择订单类型'}],
                            initialValue: 'DOING'
                        })(
                            <Select placeholder={'选择类型'} style={{width: 120}} allowClear>
                                {[{name: "正在执行", value: 'DOING'}, {name: '完成', value: 'DONE'}, {
                                    name: '取消',
                                    value: 'CANCEL'
                                }].map((item, index) => <Option value={item.value}
                                                                key={item.value}> {item.name}</Option>)}
                            </Select>
                        )}
                    </FormItem>
                    <FormItem
                    >
                        {getFieldDecorator('time', {})(
                            <RangePicker  />
                        )}
                    </FormItem>
                    <FormItem
                        label={'餐桌或包房编号'}
                    >
                        {getFieldDecorator('tableOrRoom', {})(
                            <Input/>
                        )}
                    </FormItem>
                    <FormItem
                        label={'结算员用户'}
                    >
                        {getFieldDecorator('userName', {})(
                            <Input/>
                        )}
                    </FormItem>
                    <FormItem>
                        <Button
                            type="primary"
                            htmlType="submit"
                        >
                            搜索
                        </Button>
                    </FormItem>
                </Form>
                <div className="space-bar"></div>
                <Table columns={columns} dataSource={this.state.data}
                       expandedRowRender={record => <Table columns={foodColumns} dataSource={record.items}
                                                           pagination={false}/>}
                       pagination={
                           {
                               total: this.state.total,
                               defaultPageSize: DEFAULT_PAGE_SIZE,
                               current: this.state.currentPage,
                               onChange: (current) => {
                                   this.setState({currentPage: current});
                                   this._requestData(current);
                               }
                           }
                       }/>
                <Modal visible={this.state.payBillShow} footer={null} onCancel={e => {
                    this.payBillData = {};
                    this.setState({payBillShow: false});
                }}>
                    <PayBill data={this.payBillData} success={() => {
                        this.setState({payBillShow: false});
                        this._requestData(this.page);
                    }}/>
                </Modal>
            </div>

        );
    }
}

const mapStateToPorps = state => {
    const {auth} = state.httpData;
    return {auth};
};
const mapDispatchToProps = dispatch => ({
    fetchData: bindActionCreators(fetchData, dispatch),
    receiveData: bindActionCreators(receiveData, dispatch)
});


export default connect(mapStateToPorps, mapDispatchToProps)(Form.create()(OrderList));